package com.sanpu.kxe.business.main.presenter;

import com.sanpu.kxe.business.main.bean.AdviceOutput;
import com.sanpu.kxe.business.main.contract.AdviceListContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;

import java.util.List;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：了难提交记录
 * Created by 薛勇军 on 2019/3/12.
 */

public class AdviceListPresenter implements AdviceListContract.Presenter {

    private AdviceListContract.View mView;

    private CompositeSubscription mSubscription;

    public AdviceListPresenter(AdviceListContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void getTaskList(final int page) {
        Subscription subscription = MainModel.getInstance().getTaskList(page)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<AdviceOutput>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        mView.showLoadMore(CommonConfig.LOADMOREFAIL);
                    }

                    @Override
                    public void onNext(List<AdviceOutput> adviceOutputs) {
                        if (adviceOutputs != null) {
                            mView.showTaskListView(adviceOutputs, page == 0);
                            if (adviceOutputs.size() < CommonConfig.PAGENUMER) {
                                mView.showLoadMore(CommonConfig.LOADMOREEND);
                            } else {
                                mView.showLoadMore(CommonConfig.LOADMORECOMPLETE);
                            }
                        } else {
                            mView.showLoadMore(CommonConfig.LOADMOREEND);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
